package com.xm.concurrent.base.instance;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

/**
 * 4.4.2 一个简单的数据库连接池示例
 *
 * 连接池定义
 * @author xiaoming
 * @date 2021-05-28 5:57
 */
public class ConnectionPool {
    /**
     * 双向队列维护线程池连接
     */
    private LinkedList<Connection> pool = new LinkedList<Connection>();

    /**
     *
     * @param initialSize  初始化最大上限
     */
    public ConnectionPool(int initialSize) {
        if (initialSize > 0) {
            for (int i = 0; i < initialSize; i++) {
                pool.addLast(ConnectionDriver.createConnection());
            }
        }
    }

    public void releaseConnection(Connection connection) {

    }

    /** 在 mills 内无法获取连接, 将返回 null */
    public Connection fetchConnection(long mills) throws InterruptedException {
        synchronized (pool) {
            // 完全超时
            if (mills <= 0) {
                while (pool.isEmpty()) {
                    pool.wait();
                }
                return pool.removeFirst();
            } else {
                long future = System.currentTimeMillis() + mills;
                long remaining = mills;
                while (pool.isEmpty() && remaining > 0) {
                    pool.wait(remaining);
                    remaining = future - System.currentTimeMillis();
                }
                Connection result = null;
                if (!pool.isEmpty()) {
                    result = pool.removeFirst();
                }
                return result;
            }
        }

    }

}

/**
 * 连接池驱动
 */
class ConnectionDriver{
    static class ConnectionHandler implements InvocationHandler {
        static final String COMMIT = "commit";

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (COMMIT.equals( method.getName())) {
                TimeUnit.MILLISECONDS.sleep(100);
            }
            return null;
        }
    }
    /** 创建一个 Connection 的代理, 在 commit 时休眠 100ms */
    public static final Connection createConnection() {
        return (Connection) Proxy.newProxyInstance(ConnectionDriver.class.getClassLoader(),
                new Class[]{Connection.class}, new ConnectionHandler());
    }

}
